/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief MaCI - Unit Interface Client header
 * \author Antti Maula <antti.maula@tkk.fi>
 */
#ifndef _MACI_INTERFACE_UNITCLIENT_HPP_
#define _MACI_INTERFACE_UNITCLIENT_HPP_

#include "MaCI.hpp"
#include "thread.hpp"
#include "sync.hpp"

// These are not necessarily required here, but defined to make the
// interface easier to include.
#include "UnitData.hpp"

// Forward declare gimi::GIMI
namespace gimi {
  class GIMI;
}

namespace MaCI {
  namespace Unit {
    
    // Forward declaration.
    class CUnitData;
    class CUnitClient;

    /** Callback interface class for Unit interface.
     *
     * This interface defines functions which can be used for
     * UnitClient callbacks. These functions are executed (more
     * detail per function basis) as new data arrives, and directly
     * from the context of the receiving thread. <b>Therefore, it is
     * important that the handling function is as simple and fast as
     * possible, as it will block the execution of the receiving
     * thread while executed.</b>
     */
    class CUnitClientCallback
    {
    public:

      CUnitClientCallback() {}
      virtual ~CUnitClientCallback() {}


      /** Handler function for UnitData event.
       *
       * This function is called when the UnitClient receives new
       * data from the server.
       *
       * \note <b>Keep this function simple & fast as it will block the 
       * data receiving thread while executing!</b>
       *
       * @param[in] aData       Constant reference to CUnitData element 
       *                        containing the received event.
       * @param[in] aDataSequence Sequence number of the received data. 
       *                        This should increment by one on each call.
       * @param[in] aUnitClient Reference to UnitClient 
       *                        instance which received this event.
       */
      virtual void OnUnitDataEvent(const CUnitData &aData, 
                                    const unsigned int aDataSequence,
                                    CUnitClient &aUnitClient) = 0;
    };

    /** Unit event types.
     */
    enum EUnitEvent {
      KEventUnitData = 0 ///< UnitData element received and stored.
    };


    /** MaCI - Unit Client interface.
     * 
     * This class contains the methods and types for using
     * a MaCI::Unit service in the GIMnet.
     */
    class CUnitClient 
      : private gim::CSync,
        private gim::CThread,
        public MaCI::CMaCI
    {
    public:
      /** Constructor.
       * 
       * Constructor of the UnitClient. This requires;
       * a pointer to Initialized and connected GIMI, minor
       * number of this interface (Used as GIMI minor number)
       *
       * @param[in] aGIMIPtr Pointer to GIMI used for communication
       * @param[in] aInterfaceMinor Interface minor number. Usually
       *            used to indicate the instance of devices of same
       *            type. Can be left out if MaCISL is used.
       */     
      CUnitClient(gimi::GIMI *aGIMIPtr, const int aInterfaceMinor = -1);

      
      /** Destructor.
       */
      ~CUnitClient();


      /** Get list of all different Units.
       *
       * This function returns the currently known list of available
       * units on the connected server. Optionally the call may
       * request the information directly from the server, in case the
       * application user expects the information to change during
       * class instance lifetime.
       *
       * \note The client interface fetches the list of available
       * units on Open(), so there is no need to call this function
       * with non-zero timeout, unless application really wants to
       * check the target for unit type changes.
       *

       * @param[out] aAvailableUnits List of all available units is
       *                             stored here.

       * @param[in] aTimeout_ms If this parameter is left to zero, the
       *                        function will return immediately the
       *                        currently known list of available
       *                        units.

       * @return 'true' when a list was succesfully stored to given
       *                        reference, 'false' on any error.
       */
      bool GetAvailableUnits(TAvailableUnitArray &aAvailableUnits, const unsigned int &aTimeout_ms = 0);


      /** Returns list of currently active units.
       *
       * This function returns a list of currently active units known
       * to the target UnitServer.
       *
       * \note TBD.
       *
       */
      bool GetActiveUnits();



      bool CreateUnit(TActiveUnit &aInfo, 
                      const uint32_t &aAvailableUnitId, 
                      const std::string &aName,
                      const TUnitPose &aUnitPose,
                      const unsigned int &aTimeout_ms = 0);

      bool DeleteUnit(const uint32_t &aActiveUnitId,
                      const unsigned int &aTimeout_ms = 0);


      void SetUnitClientCallback(CUnitClientCallback *aUnitClientCallback) {
        iUnitClientCallback = aUnitClientCallback;
      }

    protected:
      /** Open client interface.
       *
       * Implementation of Open() for the class. This function is
       * called by the base class CMaCI::Open() function.
       */
      EMaCIError DoOpen(void);
      
      
      /** Close client interface.
       *
       * Implementation of Close() for the class. This function is
       * called by the base class CMaCI::Close() function.
       */
      EMaCIError DoClose(void);


    private:
      /// Thread runner function. Is in charge of receiving events.
      int ThreadFunction(const int aThreadNumber);
      int ProcessMessage(const gimi::GIMIMessage &msg);
      bool SendCommand(const CUnitData &aUnitData, const int aMessageID);
      bool GetCommandReply(CUnitData &aUnitData, const int aMessageID, const int aTimeout_ms);
      //data.
      unsigned int iUnitDataSequence; ///< Received data sequence
      CUnitData iLastUnitData; ///< Last element available
      CUnitClientCallback *iUnitClientCallback; ///< Pointer to class instance containing callback functions.

      
      TAvailableUnitArray iAvailableUnitArray; ///< Available units.

      // Override copy & assignment operator privately to disable class copying.
      CUnitClient(const CUnitClient &)
        : CSync(1,1),
          CThread(1),
          CMaCI(NULL, 0, 0, ""),
          iUnitDataSequence(),
          iLastUnitData(),
          iUnitClientCallback(),
          iAvailableUnitArray() {}
      CUnitClient &operator=(const CUnitClient &) { return *this; }
    };


  }
}

#endif //_MACI_INTERFACE_UNITCLIENT_HPP_
